const router = require('koa-router')()
const userCtrl = require('../controller/user')
const util = require('../utlis/common')
const { Menu } = require('../models/menuSchema')
const { Role } = require('../models/roleSchema')
router.prefix('/users')

//添加用户
router.post('/regUser', userCtrl.userAdd)

//登录
router.get('/login', userCtrl.userFindOne)
// 用户列表
router.get('/userList', userCtrl.userFindAll)

//删除
router.post('/userDelete', userCtrl.userDel)

// 添加用户 编辑
router.post('/operate', userCtrl.userMssgerAdd)

//用户认证
router.post('/verify', userCtrl.verify)

//获取用户对应的权限菜单
router.get('/getPermissionList', async ctx => {
    let authorization = ctx.request.headers.authorization
    let { data } = util.decoded(authorization)
    let menuList = await getMenuList(data.role, data.rolelist)
    ctx.body = util.success(menuList)
})

async function getMenuList(userRole, roleKeys) {
    let rolelist = []
    let permissionList = []
    if (userRole == 0) {
        rolelist = await Menu.find({}) || []
    } else {
    //根据用户拥有的角色，获取权限列表
     let roleList = await Role.find({_id:{$in:roleKeys}})
     roleList.map(role =>{
      let {checkedKeys,halfCheckedkeys} = role.permissionList
      permissionList = permissionList.concat([...checkedKeys,...halfCheckedkeys])
    })
    permissionList =[...new Set(permissionList)] 
    rolelist = await Menu.find({_id:{$in:permissionList}})
    }
    return util.getTreeMenu(rolelist, null, [])
}


module.exports = router
